package android.demo.engine.visitor;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.demo.engine.BusinessProcess;
import android.demo.engine.RootActivity;
import android.demo.engine.tasks.ActivityTask;
import android.demo.engine.tasks.ContentProviderTask;
import android.demo.engine.tasks.ServiceBinderTask;
import android.demo.engine.tasks.ServiceStarterTask;
import android.demo.engine.tasks.ServiceTask;
import android.demo.engine.tasks.Task;

/**
 * @author  carlo
 */
public class ProcessingVisitor implements TaskVisitor{

	/**
	 * @uml.property  name="mProcess"
	 * @uml.associationEnd  
	 */
	private BusinessProcess mProcess;
	public ProcessingVisitor(BusinessProcess businessProcess) {
		this.mProcess= businessProcess;
	}

	@Override
	public void visit(ActivityTask activityTask) {
		BusinessProcess process=mProcess;
		RootActivity rAct=process.getRootActivity();
		int taskId= activityTask.getId();
		Intent i = activityTask.prepareIntent(rAct, process.getState());
		rAct.startActivityForResult(i,taskId);
	}

	@Override
	public void visit(ServiceTask serviceTask) {
		BusinessProcess process= mProcess;
		RootActivity rAct= process.getRootActivity();
		serviceTask.addServiceCompletionListener(process.getPendingTaskManager());
		Intent i= serviceTask.getIntent(rAct, process.getState());
		if(serviceTask.getType()==Task.Types.SERVICE_STARTER_TASK){
			ComponentName serviceName = rAct.startService(i);
			((ServiceStarterTask) serviceTask).manageService(serviceName);//TODO
		}else{
			ServiceBinderTask binderTask=((ServiceBinderTask) serviceTask);
			ServiceConnection conn= binderTask.getConnection(rAct);
			rAct.bindService(i, conn,binderTask.getFlags());
		}
		process.execNext(serviceTask); //TODO use notifications from root activity 
	}

	/* (non-Javadoc)
	 * @see android.demo.engine.TaskVisitor#visit(android.demo.engine.ContentProviderTask)
	 */
	public void visit(ContentProviderTask contentProviderTask) {
		// TODO Auto-generated method stub
	}
}
